package com.cv.platform.framework.web.core.interceptor;

import com.cv.framework.common.utils.servlet.ServletUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;

import static com.cv.platform.dal.redis.RedisKeyConstants.DAILY_UV;

@Component
public class UvInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String clientIP = ServletUtil.getClientIP(request);
        if (clientIP != null) {
            LocalDate today = LocalDate.now();
            String key = DAILY_UV + today;
            redisTemplate.opsForHyperLogLog().add(key, clientIP);
        }
        return true;
    }
}